package com.yyk.yykywd.mvvm.view_model

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.yyk.yykywd.mvvm.entity.MeetingBean
import com.yyk.yykywd.mvvm.entity.MeetingDetailBean
import com.yyk.yykywd.mvvm.model.MeetingModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.util.*

/**
 * 文件描述：
 * Created by guo on 2019-11-22.
 */
class MeetingInvitationViewModel : BaseViewModel() {
    private var viewModelJob = Job()
    private val uiScope = CoroutineScope(viewModelJob + Dispatchers.Main)

    var type: String = ""
    private val meetingModel = MeetingModel()
    //LiveData,使该数据可以被感知
    var mMeeting = MutableLiveData<MeetingBean>()
    var mMeetingDetail = MutableLiveData<MeetingDetailBean>()
    var mMeetings: MutableList<MeetingBean.Data> = ArrayList()

    var mCustomers: MutableList<MeetingDetailBean.Arr> = ArrayList()
    var mCustomerParts: MutableList<MeetingDetailBean.Arr> = ArrayList()
    var mCustomerAll: MutableList<MeetingDetailBean.Arr> = ArrayList()

    var detailId = ""
    var detailStatus = 0

    init {
        _status.value = BusinessApiStatus.LOADING
    }

    fun getMeetings() {
        uiScope.launch {
            meetingModel.getMeetingList(type,page.toString(), num.toString(), object : MeetingModel.GetMeetings {
                override fun getInfo(meeting: MeetingBean) {
                    meeting.data?.let { mMeetings.addAll(it) }
                    if (mMeetings.isEmpty()) {
                        _status.value = BusinessApiStatus.EMPTY
                    } else {
                        _status.value = BusinessApiStatus.DONE
                    }
                    mMeeting.value = meeting
                }

                override fun onError(e: String) {
                    _status.value = BusinessApiStatus.ERROR
                }

            })
        }
    }

    fun getMeetingDetail() {
        meetingModel.getMeetingDetail(detailId, object : MeetingModel.GetMeetingDetail {
            override fun getInfo(meetingDetail: MeetingDetailBean) {
                mCustomers.clear()
                mCustomerParts.clear()
                if (meetingDetail.arr.size >= 6) {
                    mCustomerParts.addAll(meetingDetail.arr.subList(0, 6))
                } else {
                    mCustomerParts.addAll(meetingDetail.arr)
                }
                mCustomers.addAll(mCustomerParts)
                mCustomerAll.addAll(meetingDetail.arr)
                mMeetingDetail.value = meetingDetail
            }

            override fun onError(e: String) {
            }

        })
    }

    override fun onCleared() {
        super.onCleared()
        viewModelJob.cancel()
    }
}